import React ,{ Component }from 'react';
import { Table ,Input ,Button,Icon, Modal, Form, } from 'antd';
import reqwest from 'reqwest';
const FormItem = Form.Item;
const Search = Input.Search;
let currPage=1; //保存当前页
let orderby ={field:'createDate',order:'descend' }; //记录排序列和排序的规则
let examId = null;
const columns = [{
    title: '文件名称',
    dataIndex: 'resourceName',
    key:"resourceName",
},{
    title: '文件格式',
    dataIndex: 'fileExtension',
    key:"fileExtension",
},{
    title: '更新时间',
    dataIndex: 'updateDate',
    key:"updateDate",
    sorter: true,
},{
    title: '创建时间',
    dataIndex: 'createDate',
    key:"createDate",
    sorter: true,
    /*
     render: name => `${name.first} ${name.last}`,
     */
    width: '20%',
}, {
    title: '创建人',
    dataIndex: 'createByName',
    key:"createByName",
    /* 筛选功能
     filters: [
     { text: 'Male', value: 'male' },
     { text: 'Female', value: 'female' },
     ],
     */
    width: '20%',
}];
class CollectionCreateForm extends Component{
    render(){
        return <div>
            <input type="file"  data-fileType="doc" className="files" />
             <input type="hidden" name="fileUrl"/>
            <input type="text"/>
        </div>
    }
    componentDidMount(){
            //设置回调函数
            var uploader = new VODUpload({
                // 文件上传失败
                'onUploadFailed': function (uploadInfo, code, message) {
                    console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
                },
                // 文件上传完成
                'onUploadSucceed': function (uploadInfo) {
                    console.log("onUploadSucceed: " + uploadInfo.file.name + ", oss:" + "http://" + uploadInfo.bucket + "." + uploadInfo.endpoint.substring(7) + "/" + uploadInfo.object);
                },
                // 文件上传进度，单位：字节
                'onUploadProgress': function (uploadInfo, totalSize, uploadedSize) {
                    console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(uploadedSize * 100 / totalSize) + "%");
                },
                // token超时
                'onUploadTokenExpired': function () {
                    console.console.log("onUploadTokenExpired");
                }
            });
         var baseUrl = "http://192.168.2.9:8080/learn/";//项目发布路径
        //var baseUrl = "http://192.168.2.169:8080/";//项目发布路径
            var fileType = "";//视频:video  文档:doc  图片:img
            var accessKeyId = "";
            var accessKeySecret = "";
            var inputBucket = "";// 输入OSSBucketName
            var outputBucket = "";// 输出OSSBucketName
            var objectPath = "";//工作流输入路径

            //获取请求参数(建议使用同步)
            $.ajax({
                url: baseUrl+"s/media/upload",
                data:{},// 视频:video  文档:doc  图片:img
                dataType: 'json',
                cache: false,
                async: false,
                success: function(data) {
                    if(data.status=="OK"&&data.data){
                        accessKeyId = data.data.accessKeyId;
                        accessKeySecret = data.data.accessKeySecret;
                        inputBucket = data.data.inputBucket;
                        outputBucket = data.data.outputBucket;
                        objectPath = data.data.objectPath;
                        uploader.init(accessKeyId, accessKeySecret);
                    }else {
                        alert(alert("上传初始化失败!"))
                    }
                }
            });
            $(".files").change(function (event) {
                // 逻辑代码
                var _this = $(this);
                for(var i=0; i<event.target.files.length; i++) {
                    // 逻辑代码
                    var userData = '{"Vod":{"Title":"我是标题", "Description":"我是描述", "CateId":"1", "Tags":"tag1,tag2,标签3", "UserData":"user data"}}';
                    var fileArray = event.target.files[i].name.split(".");
                    var fileFullUrl = "";
                    //获取文件名及路径
                    var fileName = "";
                    $.ajax({
                        url: baseUrl+"s/media/fileName",
                        data:{fileType :_this.attr("data-fileType"),fileSuffix :fileArray[1]},// 视频:video  文档:doc  图片:img
                        dataType: 'json',
                        cache: false,
                        async: false,
                        success: function(data) {
                            fileName = data.data.fileName;
                            objectPath = data.data.objectPath;
                            fileFullUrl = data.data.fileFullUrl;
                        },
                        error:function (data) {

                        }
                    });
                    if(fileName==""){
                        alert("fileName获取失败");
                    }
                    var fileNameFull = objectPath+"/"+ fileName+"."+fileArray[1];
                    _this.next().next().val(fileFullUrl);
                    /* _this.val(fileNameFull);
                     log(fileNameFull)*/
                    uploader.addFile(event.target.files[i], 'http://oss-cn-hangzhou.aliyuncs.com', inputBucket,  fileNameFull, userData);
                }
                uploader.startUpload();
            });
    }
}
// class CollectionCreateForm extends Component{
//       render(){
//           const formItemLayout = {
//               labelCol: {span: 12, },
//               wrapperCol:{span: 12,}
//           };
//         return  <Form onSubmit={this.handleSubmit}>
//             <input type="file"  fileType="doc" className="files" />
//             <input type="hidden" name="fileUrl"/>
//             <input type="text"/>
//         </Form>
//       }
//     componentDidMount(){}
//
// }

class Library extends React.Component {
    constructor(props){
      super(props);
      this.state = {
          data: [],
          pagination: {},
          loading: false,
          visible: false,
          selectedRowKeys: [],  // Check here to configure the default column
      };
      this.onSelectChange=this.onSelectChange.bind(this);
      this.showModal=this.showModal.bind(this);
      this.handleCancel=this.handleCancel.bind(this);
      this.handleCreate=this.handleCreate.bind(this);
      this.saveFormRef=this.saveFormRef.bind(this);
      this.fetchAdd=this.fetchAdd.bind(this);
      this.oSeach=this.oSeach.bind(this);
      this.handleTableChange=this.handleTableChange.bind(this);
      this.fetch=this.fetch.bind(this);
      this.delClick=this.delClick.bind(this);
      this.delBtn=this.delBtn.bind(this);
    };

    onSelectChange(selectedRowKeys){
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        examId = selectedRowKeys;

        if(selectedRowKeys){
            console.log("画勾被执行了")
        }
        this.setState({ selectedRowKeys });
    };

    showModal(){
        this.setState({ visible: true });
    };
    handleCancel(){
        this.setState({ visible: false });
    };
    handleCreate(){
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            values.resourceType=4;
            console.log('Received values of form: ', values);
            console.log(values);
            this.fetchAdd(values);
            form.resetFields();
            this.setState({ visible: false });
        });
    };
    saveFormRef(form){
        this.form = form;
    };

    /*异步请求  携带params（参数）*/
    fetchAdd(params = {}){
        debugger;
        console.log('params:', params);
        this.setState({ loading: true });
        reqwest({
            //url: "http://192.168.2.9:8080/learn/s/resources/hExamination/listJson",/*服务器地址*/
            url: "http://192.168.2.112:8080/s/resources/hresources/save",/*联调地址（万里）*/
            method: 'post',
            data: {
                params,
            },
            type: 'json',
        }).then(function(data){
            if(data.status=="OK"){
                debugger;
                this.fetch()
            };
        });
    };
    //搜索功能
    oSeach(value){
        this.fetch({
            orderBy:orderby.order === undefined ? undefined:orderby.order==="descend"?orderby.field+' desc':orderby.field+' asc',//把排序规则定义一下

            searchCondition:value //搜索参数
        });
        //undefined ? undefined:sorter.order==="descend"?sorter.field+' desc':sorter.field+' asc';
    };
    //表格排序，筛选，分页
    handleTableChange(pagination, filters, sorter){
        orderby.field = sorter.field; //排序的列
        orderby.order = sorter.order; //排序的规则
        const pager = this.state.pagination;  /*分页对象*/
        pager.current = pagination.current;/*分页当前页*/
        currPage=pagination.current;/*保存当前页*/
        this.setState({
            pagination: pager,/*设置分页*/
        });
        this.fetch({
            /*          sortField: sorter.field,
             sortOrder: sorter.order,*/
            pageNo: pagination.current, /*参数传给后台 当前页*/
            orderBy:sorter.order === undefined ? undefined:sorter.order==="descend"?sorter.field+' desc':sorter.field+' asc',/*改变升序降序单词（去除end）*/
            filters,
        });
    };
    /*异步请求  携带params（参数）*/
    fetch(params = {}){
        console.log('params:', params);
        this.setState({ loading: true });
        reqwest({
            //url: "http://192.168.2.9:8080/learn/s/resources/hExamination/listJson",/*服务器地址*/
            url: "http://192.168.2.112:8080/s/resources/hresources?resourceType=4",/*联调地址（万里）*/
            method: 'post',
            data: {
                params,
            },
            type: 'json',
        }).then(function(data){
            examId=null;
            const pagination = this.state.pagination;/*本地分页对象*/
            pagination.pageSize = data.data.pageSize;/*设置一页多少数据*/
            // Read total count from server
            // pagination.total = data.totalCount;
            pagination.total = data.data.count;/*设置总数据数量*/
            let list = data.data.list;
            for(let i = 0; i < list.length; i++) {
                list[i]["key"]= Number(list[i].id);
            }
            this.setState({
                loading: false,
                data: data.data.list,/*后台表格数据*/
                pagination,
                selectedRowKeys: [],

            });
        }.bind(this));
    };
    componentDidMount() {
        this.fetch();
    };

    /*删除功能*/
    delClick(){
        if (examId!=null&&examId.length>0){
            console.log(examId);
            this.delBtn({
                ids:examId.join(",")
            });
        }else {
            alert("请至少选择一道题目")
        }

    };
    delBtn (params = {}){
        console.log('params:', params);
        reqwest({
            url: "http://192.168.2.112:8080/s/resources/hresources/delete_batch",/*服务器地址*/
            //url: "http://192.168.2.176:8080/s/resources/hExamination/listJson",/*联调地址（殷龙）*/
            method: 'post',
            data: {
                params,
            },
            type: 'json',
        }).then(function(data){
            this.fetch();
        }.bind(this));
    };
    render() {
        const { selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        return (
            <div>
                <div className="N_myTree">
                   
                </div>
                <div className="N_smallContent">
                    <div className="N_handleBox">
                        <Search
                            placeholder="请输入关键字"
                            style={{ width: 200 }}
                            onSearch={this.oSeach}
                            id="seachInput"
                        />
                        <div className="btnBox">
                            <Button size="small" onClick={this.showModal}>
                                <Icon type="plus" />
                                新增</Button>
                           <CollectionCreateForm/>
                            <Button size="small"><Icon type="edit" />编辑</Button>
                            <Button size="small"><Icon type="copy" />复制</Button>
                            <Button size="small"><Icon type="export" />移动</Button>
                            <Button size="small"  onClick={this.delClick.bind(this)}><Icon type="delete" />删除</Button>
                        </div>
                    </div>
                    <Table columns={columns}
                           rowSelection={rowSelection}
                           dataSource={this.state.data} //降调取的数据转化成表格，自带属性方法
                           pagination={this.state.pagination}//分页自带属性方法
                           loading={this.state.loading}
                           onChange={this.handleTableChange}
                    />
                </div>
            </div>
        );
    }
}
export default Library